<template>
  <div>
    <!-- 搜索表单 -->
    <a-form
      ref="formRef"
      name="advanced_search"
      class="ant-advanced-search-form"
      :model="formState"
      @finish="onFinish"
    >
      <a-row :gutter="24">
        <a-col :span="8">
          <a-form-item name="username" label="用户名">
            <a-input
              v-model:value="formState.username"
              placeholder="用户名"
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item name="nickname" label="昵称">
            <a-input
              v-model:value="formState.nickname"
              placeholder="昵称"
            ></a-input>
          </a-form-item>
        </a-col>
        <a-col :span="8">
          <a-form-item name="telephone" label="手机号">
            <a-input
              v-model:value="formState.telephone"
              placeholder="手机号"
            ></a-input>
          </a-form-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :span="24" style="text-align: right">
          <!-- 新增按钮 -->
          <a-button
            type="primary"
            @click="showAddModal"
            style="margin-right: 8px"
            >新增</a-button
          >
          <!-- 查询按钮 -->
          <a-button class="query-btn" type="primary" html-type="submit">查询</a-button>
           <!-- 重置按钮 -->
          <a-button class="reset-btn" style="margin: 0 8px" @click="resetForm">重置搜索框</a-button>
          <!-- 批量删除按钮 -->
         <a-button  class="batch-delete" :class="{ selected: selectedRowKeys.length > 0 }" type="primary" @click="deleteSelectedRows">批量删除</a-button>
        </a-col>
      </a-row>
    </a-form>

    <!-- 添加用户的模态框 -->
    <a-modal
      v-model:open="isAddModalVisible"
      title="添加用户"
      :footer="undefined"
      centered
      @ok="handleAddUser"
    >
    <a-form
      ref="formRef"
      :model="addUserForm"
      :rules="addUserRules"
      @finish="handleSubmit"
    >
      <a-form-item name="username" :rules="addUserRules.username" label="用户名">
        <a-input
          v-model:value="addUserForm.username"
          placeholder="请输入用户名"
        />
      </a-form-item>
      <a-form-item name="password" label="密码">
        <a-input-password
          v-model:value="addUserForm.password"
          placeholder="请输入密码"
        />
      </a-form-item>
      <a-form-item name="confirmPassword" label="确认密码">
        <a-input-password
          v-model:value="addUserForm.confirmPassword"
          placeholder="请再次输入密码"
        />
      </a-form-item>
    </a-form>
    </a-modal>

    <!-- 批量删除的模态框 -->
    <a-modal
      v-model:open="deleteModalVisible"
      title="批量删除确认"
      :content="deleteConfirmContent"
      :ok-text="deleteOkText"
      :cancel-text="deleteCancelText"
      :ok-type="deleteOkType"
      @ok="handleBatchDelete"
      @cancel="handleDeleteCancel"
    />

    <!-- 可编辑表格 -->
    <a-table
      :columns="columns"
      :data-source="dataSource"
      :pagination="{ pageSize: 7 }"
      bordered
      :row-selection="{
        selectedRowKeys: selectedRowKeys.value,
        onChange: handleSelectionChange,
      }"
      :scroll="{ x: 1000 }"
    >
    <!--switch开关 -->
<template #isActived="{ record }">
  <a-switch
    v-model:checked="record.isActived"
    @change="handleSwitchChange(record)"
  />
</template>
      <template #bodyCell="{ column, text, record }">
        <template
          v-if="
            [
              'username',
              'nickname',
              'weixin',
              'qq',
              'telephone',
              'email',
            ].includes(column.dataIndex)
          "
        >
          <div>
            <a-input
              v-if="editableData[record.key]"
              v-model:value="editableData[record.key][column.dataIndex]"
              style="margin: -5px 0"
            />
            <template v-else>
              {{ text }}
            </template>
          </div>
        </template>
        <template v-else-if="column.dataIndex === 'operation'">
          <div class="editable-row-operations">
            <span v-if="editableData[record.key]">
              <a-typography-link @click="save(record.key)"
                >保存</a-typography-link
              >
              <a-popconfirm title="确认取消?" @confirm="cancel(record.key)">
                <template #title> 确认取消修改此行数据吗? </template>
                <a>取消</a>
              </a-popconfirm>
            </span>
            <span v-else>
              <a @click="edit(record.key)">编辑</a>
              <a-popconfirm title="确认删除?" @confirm="remove(record.key)">
                <template #title> 确认删除此行数据吗? </template>
                <a>删除</a>
              </a-popconfirm>
            </span>
          </div>
        </template>
      </template>
    </a-table>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted} from "vue";
import axios from "axios";
import { message } from "ant-design-vue";
// 添加用户的模态框可见性
const isAddModalVisible = ref(false);

// 定义表格列
const columns = [
  { title: "用户名", dataIndex: "username", width: "150px",align:'center'},
  { title: "昵称", dataIndex: "nickname", width: "180px",align:'center' },
  { title: "微信号", dataIndex: "weixin", width: "150px",align:'center' },
  { title: "QQ号", dataIndex: "qq", width: "120px",align:'center' },
  { title: "手机号", dataIndex: "telephone", width: "120px",align:'center' },
  { title: "邮箱", dataIndex: "email", width: "170px",align:'center' },
  {
    title: "启用状态",
    dataIndex: "isActived",
    width: "100px",
    align: 'center',
    slots: { customRender: 'isActived' }
  },
  { title: "操作", dataIndex: "operation",width: "106px",fixed: "right",align:'center'},
];

// 初始化数据源
const dataSource = ref([]);
const originalDataSource = ref([]); // 原始数据源

// 表单状态
const formState = reactive({
  username: "",
  nickname: "",
  weixin: "",
  qq: "",
  telephone: "",
});

// 表单引用
const formRef = ref(null);

// 编辑状态数据
const editableData = reactive({});

// 初始化渲染数据
const fetchData = async () => {
  try {
    const response = await axios.get(
      `http://localhost:5133/api/GetAllPage?page=1&pageSize=10000`
    );
    let uniqueKey = 0; // 初始化唯一键

    // 使用深拷贝初始化数据源，并为每条数据添加一个 key
    dataSource.value = response.data.data.map((item) => {
      uniqueKey++; // 自增唯一键
      return {
        ...item,
        nickname: item.nickname || "--",
        weixin: item.weixin || "--",
        qq: item.qq || "--",
        telephone: item.telephone || "--",
        email: item.email || "--",
        isActived:item.isActived,
        key: uniqueKey,
      };
    });
    originalDataSource.value = JSON.parse(JSON.stringify(dataSource.value));

    // 清空 selectedRowKeys
    // selectedRowKeys.value = [];
    console.log(response.data.data); // 查看原始API响应数据
console.log(dataSource.value); // 查看最终的dataSource状态
    
  } catch (error) {
    message.error("数据加载失败，请稍后再试！");
    console.error("Data loading failed:", error);
  }
  
};

// 在组件挂载时调用 fetchData 方法以初始化数据
onMounted(() => {
  fetchData();
});

const handleSwitchChange = async (record) => {
  try {
    // 更新后端状态
    await axios.put(`http://localhost:5133/api/Enable/${record.id}`, {
      id: record.id, // 假设记录中有id字段
      isSuccess: record.isActived,
    });
    // 如果后端更新成功，这里可以更新前端状态，但通常不需要，因为v-model已经处理了
    message.success('状态更新成功');
  } catch (error) {
    message.error('状态更新失败，请稍后再试！');
    console.error('Status update failed:', error);
    // 如果你想在失败时恢复原状态，可以这样做：
    record.isActived = !record.isActived;
  }
};

// 编辑模式
const edit = (key) => {
  // 首先清除所有现有的编辑状态
  Object.keys(editableData).forEach((k) => delete editableData[k]);

  // 然后复制选中行的数据到 editableData 中
  const recordToEdit = dataSource.value.find((item) => item.key === key);
  if (recordToEdit) {
    editableData[key] = JSON.parse(JSON.stringify(recordToEdit));
  }
  Object.entries(recordToEdit).forEach(([field, value]) => {
      // 如果字段的值为 "--"，则在 editableData 中存储该字段为空字符串
      editableData[key][field] = value === '--' ? '' : value;
    });
};

// 保存编辑
const save = async (key) => {
  console.log("save function called for key:", key); // 新增的调试信息

  // 确保 key 存在于 editableData 中
  if (!(key in editableData)) {
    console.error("Key not found in editableData");
    return;
  }

  const index = dataSource.value.findIndex((item) => item.key === key);

  if (index !== -1) {
    // 使用深拷贝来避免引用问题
    dataSource.value[index] = JSON.parse(JSON.stringify(editableData[key]));

    // 确保数据包含所有必要的字段
    const updatedRecord = dataSource.value[index];
    const dataToSend = {
      username: updatedRecord.username,
      id: updatedRecord.id,
      nickname: updatedRecord.nickname,
      avatr: "",
      telephone: updatedRecord.telephone, // 注意这里使用的是telephone字段
      email: updatedRecord.email,
      weixin: updatedRecord.weixin, //注意这里前面使用的是weixin拼音
      qq: updatedRecord.qq,
    };

    // 在发送数据前输出到控制台
    console.log("Data to send:", dataToSend);

    // 调用 API 更新服务器数据
    try {
      const response = await axios.put(
        `http://localhost:5133/api/UpdateUser/${updatedRecord.id}`,
        dataToSend
      );
      if (response.status === 200) {
        message.success("用户信息已更新");
      } else {
        message.error("更新用户信息失败");
      }
    } catch (error) {
      message.error("更新用户信息时发生错误");
      console.error("Error updating user:", error);
    }

    delete editableData[key];
  }
};
// 取消编辑
const cancel = (key) => {
  delete editableData[key];
};

// 删除操作
const remove = async (key) => {
  try {
    const userToDelete = dataSource.value.find((item) => item.key === key);
    if (!userToDelete) return;

    console.log("Deleting user with ID:", userToDelete.id);
    const response = await axios.delete(
      `http://localhost:5133/api/DelUser/${userToDelete.id}`
    );
    console.log("Response from server:", response);
    if (response.status === 200) {
      message.success("用户删除成功");
      // 更新 dataSource 和 originalDataSource
      dataSource.value = dataSource.value.filter((item) => item.key !== key);
      originalDataSource.value = originalDataSource.value.filter(
        (item) => item.key !== key
      );
    } else {
      message.error("删除用户失败");
    }
  } catch (error) {
    message.error("删除用户时发生错误");
    console.error("Error deleting user:", error);
  }
};

/////以下为批量删除

//选择状态管理
const selectedRowKeys = ref([]);

//批量删除模态框
const deleteModalVisible = ref(false);
const deleteConfirmContent = ref("您确定要删除所选的行吗?");
const deleteOkText = ref("确认删除");
const deleteCancelText = ref("取消");
const deleteOkType = ref("danger");

const handleSelectionChange = (newSelectedRowKeys) => {
  selectedRowKeys.value = newSelectedRowKeys;
  console.log("Selected Row Keys:", selectedRowKeys.value);
};
//批量删除按钮报错提示
const deleteSelectedRows = () => {
  if (selectedRowKeys.value.length === 0) {
    message.warn("请至少选择一行进行删除");
    return;
  }
  deleteModalVisible.value = true;
};
//批量删除逻辑
const handleBatchDelete = async () => {
  try {
    // 收集所有选中的uid
    const uidsToDelete = [];

    selectedRowKeys.value.forEach(key => {
      const user = dataSource.value.find(item => item.key === key);
      if (user) {
        uidsToDelete.push(user.id); // 这里假设id就是uid
        console.log("Deleting user with UID:", user.id);
      }
    });
    // 循环遍历所有选中的ID，逐个调用删除API
    for (const uid of uidsToDelete) {
      const response = await axios.delete(
        `http://localhost:5133/api/DelUser/${uid}`
      );


      if (response.status !== 200) {
        throw new Error(`Failed to delete user with UID ${uid}. Server responded with status: ${response.status}`);
      }
    }

    // 成功删除后，从数据源中移除这些项
    dataSource.value = dataSource.value.filter(
      item => !selectedRowKeys.value.includes(item.id)
    );
     // 清空selectedRowKeys并关闭模态框
     selectedRowKeys.value = [];
     deleteModalVisible.value = false;
     
    location.reload(),
    message.success("批量删除成功");
  } catch (error) {
    console.error(error);
    message.error("批量删除时发生错误");
  }
};

const handleDeleteCancel = () => {
  deleteModalVisible.value = false;
};

// 表单重置逻辑
const resetForm = () => {
  formRef.value.resetFields();
  Object.keys(formState).forEach((key) => {
    formState[key] = "";
  });
  dataSource.value = [...originalDataSource.value];
  
};

// 搜索功能
const onFinish = () => {
  console.log("Search criteria:", formState); // 添加调试信息
  const searchCriteria = Object.entries(formState)
    .filter(([_, value]) => value.trim())
    .reduce((acc, [key, value]) => ({ ...acc, [key]: value }), {});

  if (Object.keys(searchCriteria).length === 0) {
    dataSource.value = [...originalDataSource.value];
  } else {
    dataSource.value = originalDataSource.value.filter((item) =>
      Object.entries(searchCriteria).every(
        ([key, value]) => item[key]?.toLowerCase().includes(value.toLowerCase()) // 确保大小写不敏感
      )
    );
  }
};

// 添加用户的表单数据
const addUserForm = reactive({
  username: "",
  password: "",
  confirmPassword: "",
});

// 添加用户验证规则
const addUserRules = reactive({
  username: [
    { required: true, message: '请输入用户名!', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]+$/,
      message: '用户名只能包含数字或字母',
      trigger: 'blur'
    },
    {
      min: 4,
      max: 10,
      message: '用户名长度必须在4到10个字符之间',
      trigger: 'blur'
    }
  ],
  password: [
    { required: true, message: '请输入密码!', trigger: 'blur' },
    {
      pattern: /^[a-zA-Z0-9]+$/,
      message: '密码只能包含数字或字母',
      trigger: 'blur'
    },
    {
      min: 6,
      max: 12,
      message: '密码长度必须在6到12个字符之间',
      trigger: 'blur'
    }
  ],
  confirmPassword: [
    { required: true, message: '请再次输入密码!', trigger: 'blur' },
    {
      validator: (_, value, callback) => {
        if (value && value !== addUserForm.password) {
          callback(new Error('两次输入的密码不一致!'));
        } else {
          callback();
        }
      },
      trigger: 'blur'
    }
  ]
});

// 显示添加用户的模态框
const showAddModal = () => {
  isAddModalVisible.value = true;
};

// 处理添加用户
const handleAddUser = async () => {
  // 验证表单
  try {
    // 使用表单实例的validate方法来确保所有规则都通过
    await formRef.value.validate(); // 这里会触发所有表单项的验证

    // 如果验证通过，执行添加用户的逻辑
    const response = await axios.post(
      `http://localhost:5133/api/Register`,
      addUserForm
    );

    if (response.status === 200) {
      message.success("用户添加成功");
      isAddModalVisible.value = false;
      // 清空表单
      addUserForm.username = "";
      addUserForm.password = "";
      addUserForm.confirmPassword = "";

      // 刷新数据源
      location.reload();
    } else {
      message.error("用户添加失败");
    }
  } catch (error) {
    // 如果验证失败，错误会被捕获并可以在这里处理
    message.error("表单验证失败或用户添加时发生错误");
    console.error("Error adding user or validation failed:", error);
  }
};
</script>

<style scoped>
html, body {
  height: 100%;
  margin: 0;
  padding: 0;
}
.editable-row-operations a {
  margin-right: 8px;
}

.batch-delete {
  color: #000;
  background-color: #fff;
  border-color: #d9d9d9;
}

.batch-delete.selected {
  color: #fff;
  background-color: #1677ff;
}

.ant-table-cell {
  text-align: center;
}

.ant-table-column-operation .ant-table-cell {
  vertical-align: middle;
}
.ant-table-cell-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.ant-advanced-search-form {
  margin-top: -24px;
  padding-top: 15px;
}

:where(.css-dev-only-do-not-override-19iuou).ant-col-24 {
    margin-bottom: 12px;
    margin-top: -10px;
}

@media (max-width: 574px) {
  .ant-advanced-search-form .ant-row:first-child {
    display: none;
  }
  .ant-advanced-search-form .query-btn,
  .ant-advanced-search-form .reset-btn {
    display: none;
  }
}

:where(.css-dev-only-do-not-override-19iuou).ant-table-wrapper .ant-table-pagination.ant-pagination {
    margin: 12px 0 !important;
}
</style>